/**  定义用户模块相关的接口 */
const express = require("express");
const router = express.Router();
const Response = require("../utils/Response.js");


// 引入mysql连接池
const pool = require("../utils/db.js");

const jwt = require('jsonwebtoken')
const SECRET_KEY = 'JWT_SECRET_KEY'

/**
 * 处理登录业务
 */
router.post("/user/login", (req, resp) => {
  let { phone, password } = req.body
  // 查询数据库，账号密码是否填写正确
  // 执行Sql命令
  let sql = "select * from user where phone=? and password=?"
  pool.query(sql, [phone, password], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    if (result.length == 0) {
      resp.send(Response.error(1001, '手机号密码输入错误'));
    } else {
      // 获取登录用户对象
      let user = result[0]
      // 为该用户颁发一个token字符串，未来该客户端若做发送其他请求，则需要在请求Header中携带token，完成状态管理。
      let payload = { phone: user.phone, password: user.password }
      let token = jwt.sign(payload, SECRET_KEY, { expiresIn: '1d' })
      // 返回user对象与token字符串
      user.password = undefined
      resp.send(Response.ok({ user, token }));

    }
  })
});

/**
 * 处理注册业务
 */
router.post("/user/register", (req, resp) => {
  const userinfo = req.body
  // 判断数据是否合法
  if (!userinfo.phone || !userinfo.password) {
    return resp.send({ status: 1, message: '手机号或密码不能为空！' })
  }

  let sql = `select * from user where phone=?`
  pool.query(sql, [userinfo.phone], (err, results) => {
    // 执行 SQL 语句失败
    if (err) {
      return resp.send({ status: 2, message: err.message })
      //return res.cc(err)
    }
    // 大于0就说明找到该用户了，即用户名被占用
    if (results.length > 0) {
      return resp.send({ status: 3, message: '手机号被占用，请更换其他手机号！' })
      //return res.cc('用户名被占用，请更换其他用户名！')
    }
    // TODO: 用户名可用，继续后续流程...
    //执行SQL命令
    let sql = "insert into user set ?"
    pool.query(sql, [userinfo], (error, sesult) => {
      if (error) {
        resp.send(Response.error(500, error));
        throw error;
      }
      resp.send(Response.ok())
    })
  })
})

  //查询用户是否注册
  router.post("/user/select", (req, resp) => {
    let { phone } = req.body
  
    let sql = "select *  from user where phone = ?";
    pool.query(sql, [phone], (error, result) => {
      if (error) {
        resp.send(Response.error(500, error));
        throw error;
      }
      if (result.length===0) {
        resp.send(Response.error(403, '该用户暂未注册'));
      } else {
        resp.send(Response.ok('用户已注册'));
      }
  
    });
  })
  




// 将router对象导出
module.exports = router;
